const fs = require('fs');
const axios = require('axios');

// 读取 GeoJSON 文件
function readGeoJSON(filePath) {
  const data = fs.readFileSync(filePath, 'utf8');
  return JSON.parse(data);
}

// 提取所需属性并返回一个数组
function extractProperties(features) {
  const result = [];
  features.forEach(feature => {
    const properties = feature.properties;

    // 检查是否存在所需的属性
    if (properties && properties.parent && properties.parent.adcode !== undefined && properties.name !== undefined && properties.adcode !== undefined) {
      result.push({

        parentCode: properties.parent.adcode,
        name: properties.name,
        code: properties.adcode,
        geojson: `https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=${properties.adcode}_full`,

        // label: properties.name.replace('市', ''),
        // value: String(properties.adcode),
        // jsonName: String(properties.adcode),
        // areaLevel: 'city',
        // areaKey: 'JN',
        // areaCode: String(properties.adcode),
      });
    } else {
      console.warn('Skipping feature due to missing properties:', feature);
    }
  });
  return result.sort((a, b) => a.value * 1 - b.value * 1);
}

// 发送 HTTP 请求并保存响应数据到文件
async function fetchAndSaveData(item) {
  try {
    const response = await axios.get(item.geojson);
    const filePath = `./geojson/山西省/${item.code}.json`;
    fs.writeFileSync(filePath, JSON.stringify(response.data, null, 0));
    console.log(`Saved data for ${item.code} to ${filePath}`);
  } catch (error) {
    console.error(`Failed to fetch or save data for ${item.code}:`, error.message);
  }
}

// 循环处理 extractedData 数组，每个二秒钟调用一次
async function processExtractedData(extractedData) {
  for (let i = 0; i < extractedData.length; i++) {
    const item = extractedData[i];
    console.log(`Processing item ${i + 1}/${extractedData.length}:`, item);

    // 调用 fetchAndSaveData 并等待其完成
    await fetchAndSaveData(item);

    // 如果不是最后一个元素，则等待2秒后继续
    if (i < extractedData.length - 1) {
      await new Promise(resolve => setTimeout(resolve, 2000));
    }
  }
  console.log('All items processed.');
}

// 主函数
function processGeoJSON(inputFilePath, outputFilePath) {
  // 读取 GeoJSON 文件
  const geojsonData = readGeoJSON(inputFilePath);
  // 提取所需的属性
  const extractedData = extractProperties(geojsonData.features);
  console.log(extractedData);
  // 处理 extractedData 数组
  processExtractedData(extractedData);
}

// 使用示例
const inputFilePath = './geojson/山西省城市.json'; // 替换为你的 GeoJSON 文件路径

processGeoJSON(inputFilePath);

